package com.harmonypilot.modelconfig.crypto;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

@Component
public class CryptoService {
    private final SecretKey key;
    private final SecureRandom random = new SecureRandom();

    public CryptoService(@Value("${modelcfg.crypto.key}") String secret) {
        if (secret == null || secret.length() < 16) {
            throw new IllegalStateException("modelcfg.crypto.key must be configured with a strong secret");
        }
        byte[] k = sha256(secret);
        this.key = new SecretKeySpec(k, "AES");
    }

    public String encrypt(String plain) {
        try {
            byte[] iv = new byte[12];
            random.nextBytes(iv);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
            byte[] enc = cipher.doFinal(plain.getBytes());
            byte[] out = new byte[12 + enc.length];
            System.arraycopy(iv, 0, out, 0, 12);
            System.arraycopy(enc, 0, out, 12, enc.length);
            return Base64.getEncoder().encodeToString(out);
        } catch (Exception e) { throw new RuntimeException(e); }
    }

    public String decrypt(String token) {
        try {
            byte[] all = Base64.getDecoder().decode(token);
            byte[] iv = new byte[12];
            byte[] enc = new byte[all.length - 12];
            System.arraycopy(all, 0, iv, 0, 12);
            System.arraycopy(all, 12, enc, 0, enc.length);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
            return new String(cipher.doFinal(enc));
        } catch (Exception e) { throw new RuntimeException(e); }
    }

    private static byte[] sha256(String s) {
        try {
            return java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes());
        } catch (Exception e) { throw new RuntimeException(e); }
    }
}


